package cn.edu.nju.software.android.adapter;

import java.util.ArrayList;

import cn.edu.nju.software.android.activity.CommentActivity;
import cn.edu.nju.software.android.activity.DetailedWeiboActivity;
import cn.edu.nju.software.android.activity.PictureActivity;
import cn.edu.nju.software.android.activity.R;
import cn.edu.nju.software.android.activity.RetweetActivity;
import cn.edu.nju.software.android.model.Status;
import cn.edu.nju.software.android.model.User;
import cn.edu.nju.software.android.util.AsyncImageLoader;
import cn.edu.nju.software.android.util.DateHelper;
import cn.edu.nju.software.android.util.ImageUtil;
import me.maxwin.view.IListviewCallback;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class PersonalStatusListViewAdapter extends ArrayAdapter<Status>{
	private User user;
	private Context context;
	private ArrayList<Status> statuses = new ArrayList<Status>();
	private int nowCount = 0;
	private Button followButton;

	private Handler failureHandler = new Handler(){
		public void handleMessage(Message msg) {
			Toast.makeText(context, "WIFI没有打开", Toast.LENGTH_SHORT).show();
		}
	};
	
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			notifyDataSetChanged(); //发送消息通知ListView更新
			nowCount += msg.what;
			((IListviewCallback)context).onComplete();
			if(nowCount >= user.getStatusesCount()){
				((IListviewCallback)context).disableLoadFunction();
			}else{
				((IListviewCallback)context).enableLoadFunction();
			}
		}
	};

	private Handler friendShipHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(followButton != null){
				if(followButton.getText().equals("取消关注")){
					followButton.setText("关注");
					user.setFollowing(false);
				}
				else{
					followButton.setText("取消关注");
					user.setFollowing(true);
				}
			}
		}
	};

	public PersonalStatusListViewAdapter(User user, Context context) {
		super(context, R.layout.layout_user);
		this.context = context;
		this.user = user;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(position == 0){
			convertView = inflater.inflate(R.layout.layout_user_detail, parent, false);
			ImageView userImageView = (ImageView)convertView.findViewById(R.id.head);
			TextView userTextView = (TextView)convertView.findViewById(R.id.name);
			TextView descriptionTextView = (TextView)convertView.findViewById(R.id.description);
			followButton = (Button)convertView.findViewById(R.id.follow);
			TextView weiboNumTextView = (TextView)convertView.findViewById(R.id.weibo_num);
			TextView followerTextView = (TextView)convertView.findViewById(R.id.following_me_num);
			TextView friendTextView = (TextView)convertView.findViewById(R.id.followed_by_me_num);

			AsyncImageLoader userImageAsyLoader = new AsyncImageLoader();
			Drawable userCachedImage = userImageAsyLoader.loadDrawable(context,failureHandler, user.getAvatar_large(), userImageView,
					new AsyncImageLoader.ImageCallback() {
				@Override
				public void imageLoaded(Drawable imageDrawable,
						ImageView imageView, String imageUrl) {
					if(imageDrawable != null)
						imageView.setImageDrawable(imageDrawable);
				}
			},100, 100);
			if (userCachedImage == null) {
				userImageView.setImageResource(R.drawable.user);
			} else {
				userImageView.setImageDrawable(userCachedImage);
			}
			userTextView.setText(user.getName());
			descriptionTextView.setText(user.getDescription());
			if(user.isFollowing()){
				followButton.setText("取消关注");
			}else{
				followButton.setText("关注");
			}
			followButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(!user.isFollowing()){
						user.createFriendship(friendShipHandler);
					}else{
						user.destroyFriendship(friendShipHandler);
					}
				}
			});
			followButton.setOnTouchListener(new OnTouchListener(){     
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						((Button) v).setTextColor(context.getResources().getColor(R.color.white));
					} else {
						((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					}
					return false;
				}
			});
			weiboNumTextView.setText("微博:"+countApproximate(user.getStatusesCount()));
			followerTextView.setText("粉丝:"+countApproximate(user.getFollowersCount()));
			friendTextView.setText("关注:"+countApproximate(user.getFriendsCount()));

		}else{
			final Status s = statuses.get(position-1);
			TextView userTextView = null;
			TextView textView = null;
			ImageView subImageView = null;
			TextView dateTextView = null;
			Button commentButton = null;
			Button retweetButton = null;
			TextView locationTextView = null;
			TextView sourceTextView = null;
			Button originalUserNameButton = null;
			TextView retweetedTextView = null;
			if (s.getRetweetStatus() == null) {
				convertView = inflater.inflate(
						R.layout.listview_personalstatus_original, parent, false);
				userTextView = (TextView) convertView
						.findViewById(R.id.personal_name_original);
				textView = (TextView) convertView
						.findViewById(R.id.personal_content_original);
				subImageView = (ImageView) convertView
						.findViewById(R.id.personal_picture_original);
				dateTextView = (TextView) convertView
						.findViewById(R.id.personal_time_original);
				locationTextView = (TextView)convertView.findViewById(R.id.personal_location_original);
				sourceTextView = (TextView)convertView.findViewById(R.id.personal_source_original);
				commentButton = (Button) convertView
						.findViewById(R.id.personal_comment_original);
				retweetButton = (Button) convertView
						.findViewById(R.id.personal_retweet_original);
				setListViewListener(convertView, false,s);
			} else {
				convertView = inflater.inflate(
						R.layout.listview_personalstatus_retweeted, parent, false);
				userTextView = (TextView) convertView
						.findViewById(R.id.personal_name_retweeted);
				textView = (TextView) convertView
						.findViewById(R.id.personal_link_retweeted);
				originalUserNameButton = (Button) convertView
						.findViewById(R.id.personal_originalName_retweeted);
				retweetedTextView = (TextView) convertView
						.findViewById(R.id.personal_content_retweeted);
				subImageView = (ImageView) convertView
						.findViewById(R.id.personal_picture_retweeted);
				dateTextView = (TextView) convertView
						.findViewById(R.id.personal_time_retweeted);
				locationTextView = (TextView)convertView.findViewById(R.id.personal_location_retweeted);
				sourceTextView = (TextView)convertView.findViewById(R.id.personal_source_retweeted);
				commentButton = (Button) convertView
						.findViewById(R.id.personal_comment_retweeted);
				retweetButton = (Button) convertView
						.findViewById(R.id.personal_retweet_retweeted);
				setListViewListener(convertView,true,s);
			}
			AsyncImageLoader subImageAsyLoader = new AsyncImageLoader();			

			if (s.getRetweetStatus() != null) {
				User u = s.getRetweetStatus().getUser();
				if(u != null)
					originalUserNameButton.setText(u.getName());
				else
					originalUserNameButton.setText("");
				if (s.getRetweetStatus().getThumbnail_pic() != null) {
					Drawable subCachedImage = subImageAsyLoader.loadDrawable(context,failureHandler, s
							.getRetweetStatus().getThumbnail_pic(),
							subImageView,
							new AsyncImageLoader.ImageCallback() {
						@Override
						public void imageLoaded(Drawable imageDrawable,
								ImageView imageView, String imageUrl) {
							imageView
							.setImageDrawable(ImageUtil.resizeStatusPic(imageDrawable));
						}

					},1, 500);
					if (subCachedImage == null) {
						subImageView.setImageResource(R.drawable.loading);
					}else {
						subImageView.setImageDrawable(subCachedImage);
					}
				}else{
					LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.personal_retweet_layout);
					int index = layout.indexOfChild(subImageView);
					layout.removeViewAt(index);
				}
				retweetedTextView.setText(s.getRetweetStatus().getText());
				if(s.getGeo() != null){
					locationTextView.setText("维度:"+s.getGeo().getLatitude() + ",经度:" + s.getGeo().getLongtitude());
				}else{
					LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.personal_retweet_layout);;
					int index = layout.indexOfChild(locationTextView);
					layout.removeViewAt(index);
				}
			}else{
				if (s.getThumbnail_pic() != null) {
					Drawable subCachedImage = subImageAsyLoader.loadDrawable(context,failureHandler,
							s.getThumbnail_pic(), subImageView,
							new AsyncImageLoader.ImageCallback() {
						@Override
						public void imageLoaded(Drawable imageDrawable,
								ImageView imageView, String imageUrl) {
							imageView.setImageDrawable(ImageUtil.resizeStatusPic(imageDrawable));
						}

					},1, 500);
					if (subCachedImage == null) {
						subImageView.setImageResource(R.drawable.loading);
					} else {
						subImageView.setImageDrawable(ImageUtil.resizeStatusPic(subCachedImage));
					}
				}else{
					LinearLayout layout = (LinearLayout) convertView;
					int index = layout.indexOfChild(subImageView);
					layout.removeViewAt(index);
				}
				if(s.getGeo() != null){
					locationTextView.setText("维度:"+s.getGeo().getLatitude() + ",经度:" + s.getGeo().getLongtitude());
				}else{
					LinearLayout layout = (LinearLayout) convertView;
					int index = layout.indexOfChild(locationTextView);
					layout.removeViewAt(index);
				}
			}
			if(s.getGeo() != null){
				locationTextView.setText(s.getGeo().getAddress());
			}else{
				locationTextView.setText("");
			}
			sourceTextView.setText("来自"+s.getSource());
			userTextView.setText(s.getUser().getName());
			dateTextView.setText(DateHelper.getDateStr(s.getCreatedAt()));
			textView.setText(s.getText());
			commentButton.setText("评论(" + s.getCommentsCount() + ")");
			retweetButton.setText("转发(" + s.getRepostsCount() + ")");
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, DetailedWeiboActivity.class);
					intent.putExtra("status", s);
					intent.putExtra("user", user);
					context.startActivity(intent);
				}
			});
		}
		return convertView;
	}

	private String countApproximate(int followersCount) {
		int grade1 = 100000000;
		int grade2 = 10000;
		if(followersCount>=grade1)
			return followersCount / grade1 + "亿";
		if(followersCount>=grade2)
			return followersCount / grade2 + "万";
		return followersCount+"";
	}

	@Override
	public int getCount() {
		return statuses.size() + 1;
	}

	@Override
	public Status getItem(int position) {
		// TODO Auto-generated method stub
		return statuses.get(position);
	}


	public void loadMoreStatuses(){
		long sinceId = 0;
		if(statuses.size() != 0)
			sinceId = statuses.get(0).getId();
		Status.downloadMorePersonalStatus(user.getId(), sinceId, statuses, handler);
	}

	private void setListViewListener(View view, final boolean isRetweet, final Status s) {
		view.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					int touch = context.getResources().getColor(R.color.touch);
					v.setBackgroundColor(touch);
					if (isRetweet) {
						v.findViewById(R.id.personal_name_retweeted).setBackgroundColor(touch);
						v.findViewById(R.id.personal_retweet_layout).setBackgroundColor(touch);
						View child = v.findViewById(R.id.personal_picture_retweeted);
						if(child != null)
							child.setBackgroundColor(touch);
					} else {
						v.findViewById(R.id.personal_name_original).setBackgroundColor(touch);
						View child = v.findViewById(R.id.personal_picture_original);
						if(child != null)
							child.setBackgroundColor(touch);
					}

				} else {
					int white = context.getResources().getColor(R.color.white);
					v.setBackgroundColor(white);
					if (isRetweet) {
						v.findViewById(R.id.personal_name_retweeted).setBackgroundColor(white);
						v.findViewById(R.id.personal_retweet_layout).setBackgroundColor(white);
						View child = v.findViewById(R.id.personal_picture_retweeted);
						if(child != null)
							child.setBackgroundColor(white);

					} else {
						v.findViewById(R.id.personal_name_original).setBackgroundColor(white);
						View child = v.findViewById(R.id.personal_picture_original);
						if(child != null)
							child.setBackgroundColor(white);
					}
				}
				return false;
			}
		});

		Button name = null;
		if (isRetweet) {
			name = (Button) view.findViewById(R.id.personal_name_retweeted);
		} else {
			name = (Button) view.findViewById(R.id.personal_name_original);
		}
		name.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.gray));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
				}
				return false;
			}
		});

		ImageButton picture = null;
		if (isRetweet) {
			picture = (ImageButton) view.findViewById(R.id.personal_picture_retweeted);
		} else {
			picture = (ImageButton) view.findViewById(R.id.personal_picture_original);
		}
		if (picture != null) {
			picture.setOnTouchListener(new OnTouchListener(){     
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						Intent intent = new Intent(context, PictureActivity.class);
						if(!isRetweet)
							intent.putExtra("picture", s.getOriginal_pic());
						else{
							intent.putExtra("picture", s.getRetweetStatus().getOriginal_pic());
						}
						context.startActivity(intent);
					}
					return false;
				}
			});
		}

		Button comment = null;
		if (isRetweet) {
			comment = (Button) view.findViewById(R.id.personal_comment_retweeted);
		} else {
			comment = (Button) view.findViewById(R.id.personal_comment_original);
		}
		comment.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, CommentActivity.class);
					intent.putExtra("isReply", false);
					intent.putExtra("status_id", s.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

		Button retweet = null;
		if (isRetweet) {
			retweet = (Button) view.findViewById(R.id.personal_retweet_retweeted);
		} else {
			retweet = (Button) view.findViewById(R.id.personal_retweet_original);
		}
		retweet.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, RetweetActivity.class);
					intent.putExtra("status_id", s.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

	}
}
